from flask import render_template, redirect,request,url_for,flash
from flask_login import login_user,logout_user,login_required,current_user
from app.auth import auth
from app import db
from app.models import User
from app.auth.forms import LoginForm,RegistrationForm,ChangePasswordForm

@auth.before_app_request
def before_request():
    if current_user.is_authenticated:
        current_user.ping()

@auth.route('/login',methods=['GET','POST'])
def login():
    form=LoginForm()
    if form.validate_on_submit():
        user=User.query.filter_by(name=form.name.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user,form.remember_me.data)
            return redirect(request.args.get('next') or url_for('main.index'))
        flash('错误用户名或密码')
    return render_template('auth/login.html',form=form)

@auth.route('logout')
@login_required
def logout():
    logout_user()
    flash('你已登出')
    return redirect(url_for('main.index'))

@auth.route('/register',methods=['GET','POST'])
def register():
    form=RegistrationForm()
    if form.validate_on_submit():
        user=User(name=form.name.data,password=form.password.data,note_name=form.note_name.data)
        db.session.add(user)
        try:
            db.session.commit()
        except:
            flash('无法添加注册的用户到后台')
            db.session.rollback()
        token=user.generate_confirmation_token()
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html',form=form)

@auth.route('/change_password',methods=['GET','POST'])
@login_required
def change_password():
    form=ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.old_password.data):
            current_user.password=form.password.data
            db.session.add(current_user)
            try:
                db.session.commit()
                flash('你的密码已更新')
            except:
                flash('无法更新你的密码到后台')
                db.session.rollback()
        else:
            flash('旧密码错误')
    return render_template('auth/change_password.html',form=form)